import path from "path";
import fs from "fs";
import {
  maxSize,
  ext,
  checkOutput,
  getImageList,
  fileUpload,
  downloadImage,
} from "./utils";

// 获取用户输入
// const input = String(process.argv[2]) || null;
// const deep = Boolean(process.argv[3] === "-deep");
// const output = String(process.argv[process.argv.length - 1]) || null;
// 方法调用
// thankTinyPng(input, deep, output);
// 方法实现
function thankTinyPng(input, deep, output, callback, logInfo) {
  // 日志打印
  const log = {
    warning(title, ...content) {
      console.log(`\x1b[33m${title}\x1b[33m \x1b[0m`, ...content);
      logInfo(
        `\n<div style="color: orange">${title}\n${content}</div>`
      );
    },
    success(title, ...content) {
      console.log(`\x1b[32m${title}\x1b[32m \x1b[0m`, ...content);
      logInfo(
        `\n<div style="color: green">${title}\n${content}</div>`
      );
    },
    error(title, ...content) {
      console.log(`\x1b[31m${title}\x1b[31m \x1b[0m`, ...content);
      logInfo(
        `\n<div style="color: red">${title}\n${content}</div>`
      );
    },
  };

  const root = process.cwd(); // 根目录
  // 必须输入一个有效的文件/文件夹
  if (!input) throw new Error("请输入一个有效的文件/文件夹");
  // 配置表
  const option = {
    README: "仅支持大小不超过 5MB 的 png/jpg 文件",
    maxSize,
    ext,
    root,
    deep,
    input: path.relative(root, input),
    output: output === input || output === "-deep" ? null : output,
    imageList: [],
    imageCount: 0,
    successCount: 0,
  };
  // 检查
  checkOutput(option.output).then((output) => {
    option.output = output;
    // 获取处理文件列表
    option.imageList = getImageList(option, log);
    option.imageCount = option.imageList.length;
    log.success("当前配置信息：", JSON.stringify(option));
    // 遍历
    option.imageList.forEach((imgUrl) => {
      // 上传
      fileUpload(imgUrl, log).then((serverReq) => {
        let preUrl = "";
        try {
          preUrl = serverReq.output.url;
        } catch(error) {
          log.error(error)
        }
        const webImgUrl = path.join(preUrl, path.basename(imgUrl));
        // 下载
        downloadImage(webImgUrl, log).then((binary) => {
          let outputPath = imgUrl;
          let { output, input } = serverReq || {};
          let { ratio: outputRatio = 0, size: outputSize = 0 } = output || {};
          let { size: inputSize = 0 } = input || {};
          // 指定输出文件夹
          if (option.output) {
            outputPath = path.join(option.output, path.basename(imgUrl));
          }
          // 写入
          fs.writeFile(outputPath, binary, "binary", (err) => {
            if (err) return log.error("警告：写入失败, 当前文件", outputPath);
            option.successCount++;
            let msg = "";
            msg += `文件[${option.successCount}]: ${imgUrl}`;
            msg += `原始大小: ${(inputSize / 1024).toFixed(2)}KB\n`;
            msg += `压缩大小: ${(outputSize / 1024).toFixed(2)}KB\n`;
            msg += `优化比例: ${((1 - outputRatio) * 100).toFixed(2)}%\n`;
            !callback && log.success("成功：压缩完成", msg);
            callback && callback(msg + "成功：压缩完成\n");
          });
        }, log.error);
      }, log.error);
    });
  }, log.warning);
}

export default thankTinyPng;
